import {history, Outlet, useLocation} from 'umi';
import styles from './index.less';
import React, {useMemo, useState} from 'react';
import ThemeCut from './components/theme-cut';
import {
    IconBookmark,
    IconExit,
    IconHash,
    IconHome,
    IconKey,
    IconList,
    IconMail,
    IconPriceTag,
    IconUser
} from '@douyinfe/semi-icons';
import {Avatar, Button, Dropdown, Form, Modal, Nav, Toast} from "@douyinfe/semi-ui";
import {clearToken, getToken, saveToken} from "@/unils/token";
import AuthUser from '@/api/model/users';
// 检测系统的暗黑模式
const mql = window.matchMedia('(prefers-color-scheme: dark)');

function matchMode(e: any) {
    const body = document.body;
    if (e.matches) {
        if (!body.hasAttribute('theme-mode')) {
            body.setAttribute('theme-mode', 'dark');
        }
    } else {
        if (body.hasAttribute('theme-mode')) {
            body.removeAttribute('theme-mode');
        }
    }
}

mql.addListener(matchMode);


export default class Layout extends React.Component {
    child: any;

    constructor(props: {} | Readonly<{}>) {
        super(props);
        console.log('history', history.location.pathname)
        this.state = {
            // @ts-ignore
            token: '',
            isUpdate: false,
        };
        this.changeUpdate = this.changeUpdate.bind(this)
    }

    // 跳转主页
    goHome = () => {
        history.push('/')
    }

    // 跳转关于
    goAbout = () => {
        history.push('/about')
    }

    switchMode = () => {
        const body = document.body;
        if (body.hasAttribute('theme-mode')) {
            body.removeAttribute('theme-mode');
            // 以下这行代码，window.setMode仅用于当通过本Demo切换时，通知Semi官网Header记录更新当前模式（只用于演示）。在您的代码里无需存在。
            // window?.setMode('light');
            this.setState({ is_theme_mode: false });
            sessionStorage.setItem('is_theme_mode', 'false');
        } else {
            body.setAttribute('theme-mode', 'dark');
            // window.setMode('dark');
            this.setState({ is_theme_mode: true });
            sessionStorage.setItem('is_theme_mode', 'true');
        }
    };

    change_is_theme_mode = () => {
        if (!document.body.hasAttribute('theme-mode')) {
            this.setState({ is_theme_mode: false });
        } else {
            this.setState({ is_theme_mode: true });
        }
        if (sessionStorage.getItem('is_theme_mode') == 'true') {
            document.body.setAttribute('theme-mode', 'dark');
        } else {
            document.body.removeAttribute('theme-mode');
        }
    };
    // 强制更新header
    changeUpdate() {
        const token = getToken();
        this.setState({
            token,
        });
        console.log('this.state', this.state)
        const {isUpdate}: any = this.state;
        this.setState({isUpdate: !isUpdate});
    }

    componentDidMount() {
        this.change_is_theme_mode();

        const token = getToken();
        this.setState({
            token,
        });
    }

    onLoginDialogRef(ref: any) {
        this.child = ref;
    }

    // 点击登陆按钮
    clickLoginBtn = (e: any) => {
        this.child.showLoginDialog();
    };

    render() {
        const {token}: any = this.state;
        return (
            <div className={styles.container}>
                <div className={styles.header}>
                    <div onClick={this.goHome} className={styles.logo}>Prvideo</div>
                    <div className={styles.icons_content}>
                        <IconHome onClick={this.goHome} className={styles.icon_style}/>
                        <ThemeCut switchMode={this.switchMode}/>
                        <span className={styles.about} onClick={this.goAbout}>
                            关于
                        </span>
                        {!token ? (
                            <Button
                                theme="solid"
                                type="secondary"
                                onClick={this.clickLoginBtn}
                            >
                                登陆
                            </Button>
                        ) : (
                            <AvatarInfo changeUpdate={this.changeUpdate}/>
                        )}
                    </div>
                </div>
                {
                    location.pathname.indexOf('/admin') !== -1 ?
                        <div className={styles.admin_conents_container}>
                            <NavApp/>
                            <div style={{padding: 0}}
                                 className={['content_container', styles.content_container, styles.admin_conents].join(' ')}>
                                <Outlet/>
                            </div>
                        </div>
                        : <div className={['content_container', styles.content_container].join(' ')}>
                            <Outlet/>
                        </div>
                }
                {/*  登陆对话框*/}
                <LoginDialog
                    onLoginRef={(e: any) => this.onLoginDialogRef(e)}
                    changeUpdate={this.changeUpdate}
                />
            </div>
        );
    }
}

function NavApp(props = {}) {
    const location = useLocation();
    const [openKeys, setOpenKeys] = useState(['/admin/bookmarkConfig']);
    let [selectedKeys, setSelectedKeys] = useState([location.pathname]);
    const [isCollapsed, setIsCollapsed] = useState(false);
    selectedKeys = [location.pathname];

    const onSelect = (data: any) => {
        history.push(data.itemKey);
        console.log('data', data);
        setSelectedKeys([...data.selectedKeys]);
    };

    const onOpenChange = (data: any) => {
        console.log('trigger onOpenChange: ', data);
        setOpenKeys([...data.openKeys]);
    };

    const onCollapseChange = (isCollapsed: any) => {
        console.log('isCollapsed', isCollapsed);
        setIsCollapsed(isCollapsed);
    };

    const items = useMemo(
        () => [
            {itemKey: '/admin', text: '控制台', icon: <IconUser/>},
            {
                itemKey: '/admin/bookmarkConfig',
                text: '书签管理',
                icon: <IconBookmark/>,
                items: [
                    {
                        icon: <IconPriceTag/>,
                        itemKey: '/admin/classify',
                        text: '分类管理',
                    },
                    {
                        icon: <IconList/>,
                        itemKey: '/admin/video',
                        text: '视频列表',
                    },
                    {
                        icon: <IconList/>,
                        itemKey: '/admin/banner',
                        text: '轮播图列表',
                    },
                ],
            },
        ],
        [],
    );

    return (
        <Nav
            isCollapsed={isCollapsed}
            openKeys={openKeys}
            selectedKeys={selectedKeys}
            bodyStyle={{height: 320}}
            items={items}
            footer={{
                collapseButton: true,
            }}
            onCollapseChange={onCollapseChange}
            onOpenChange={onOpenChange}
            onSelect={onSelect}
        />
    );
}


const AvatarInfo = (props: any) => {
    // const {user}: any = useModel(
    //     'user',
    //     (model: { user: any; setuserInfo: any }) => ({
    //         user: JSON.parse(window.localStorage.getItem('userinfo') as string),
    //     }),
    // );

    const layoutExit = () => {
        history.push('/');
        clearToken();
        props.changeUpdate();
    };

    const goAdminPage = () => {
        history.push('/admin');
    };

    const goUser = () => {
        history.push('/user');
    };

    return (
        <Dropdown
            trigger={'click'}
            position={'bottomLeft'}
            clickToHide={true}
            render={
                <Dropdown.Menu>
                    {/*<Dropdown.Item icon={<IconUser/>} onClick={goUser}>*/}
                    {/*    个人中心*/}
                    {/*</Dropdown.Item>*/}
                    {/*<Dropdown.Item icon={<IconUserGroup/>} onClick={goAdminPage}>*/}
                    {/*    后台管理*/}
                    {/*</Dropdown.Item>*/}
                    <Dropdown.Item icon={<IconExit/>} onClick={layoutExit}>
                        退 出
                    </Dropdown.Item>
                </Dropdown.Menu>
            }
        >
            <Avatar size="small" src='//technique-1251242649.cos.ap-beijing.myqcloud.com/image/jpeg/avatard.jpg'
                    style={{margin: 4}}/>
        </Dropdown>
    );
};

type Props = {
    onLoginRef: any;
    changeUpdate: any;
};

class LoginDialog extends React.Component<Props> {
    constructor(props: any) {
        super(props);
        this.state = {
            // @ts-ignore
            visible: false,
            register: false,
            title: '登陆',
            getEmailCode: '发送邮箱',
            isGetEmailCode: false,
            email: '',
        };
        this.showLoginDialog = this.showLoginDialog.bind(this);
        this.goRegister = this.goRegister.bind(this);
        this.handleOkLogin = this.handleOkLogin.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.sendEmail = this.sendEmail.bind(this);
        this.changeEmail = this.changeEmail.bind(this);
    }

    componentDidMount() {
        this.props.onLoginRef(this);
    }

    showLoginDialog() {
        this.setState({
            visible: true,
        });
    }

    changeEmail(email: string) {
        this.setState({
            email,
        });
    }

    goRegister() {
        const {register}: any = this.state;
        this.setState({
            register: !register,
            title: register ? '登陆' : '注册',
        });
    }

    handleOkLogin() {
        this.setState({
            visible: false,
        });
        this.props.changeUpdate();
    }

    handleCancel(e: any) {
        this.setState({
            visible: false,
        });
    }

    async sendEmail(e: any) {
        const {email}: any = this.state;
        const match =
            /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
        if (!match.test(email)) {
            Toast.error({
                content: '请输入正确的邮箱！',
                duration: 3,
            });
        } else {
            const res: any = await AuthUser.SendEmail({email});
            if (res.status) {
                Toast.success({
                    content: '发送邮箱成功！',
                    duration: 3,
                });
                let time = 59;
                let timer = setInterval(() => {
                    if (time == 0) {
                        clearInterval(timer);
                        this.setState({
                            isGetEmailCode: false,
                            getEmailCode: '发送邮箱',
                        });
                    } else {
                        this.setState({
                            isGetEmailCode: true,
                            getEmailCode: time + '秒后重试',
                        });
                        time--;
                    }
                }, 1000);
            } else {
                Toast.error({
                    content: res.data.error,
                    duration: 3,
                });
            }
        }
    }

    render() {
        const {visible, title, register, getEmailCode, isGetEmailCode}: any =
            this.state;
        return (
            <>
                <Modal
                    title={title}
                    visible={visible}
                    hasCancel={false}
                    closable={false}
                    footer={''}
                    className="modalStyle"
                    onCancel={this.handleCancel}
                >
                    <div style={{paddingBottom: '1rem'}}>
                        <LoginForm
                            handleOkLogin={() => {
                                this.handleOkLogin();
                            }}
                            getEmailCode={getEmailCode}
                            isGetEmailCode={isGetEmailCode}
                            isregister={register}
                            goRegister={this.goRegister}
                            sendEmail={(e: any) => {
                                this.sendEmail(e);
                            }}
                            changeEmail={(e: string) => {
                                this.changeEmail(e);
                            }}
                        />
                    </div>
                </Modal>
            </>
        );
    }
}

const LoginForm = (props: any) => {
    // const {setuserInfo}: any = useModel(
    //     'user',
    //     (model: { user: any; setuserInfo: any }) => ({
    //         setuserInfo: model.setuserInfo,
    //     }),
    // );
    const register = () => {
        props.goRegister();
    };
    // 验证规则
    const rules = (values: any) => {
        let isNext = true;
        const match =
            /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
        if (!values.email || !values.password) {
            Toast.error({
                content: '请输入账号和密码！',
                duration: 3,
            });
            isNext = false;
        } else {
            if (props.isregister) {
                if (!values.verify_key) {
                    Toast.error({
                        content: '请输入验证码！',
                        duration: 3,
                    });
                    isNext = false;
                } else {
                    if (!match.test(values.email)) {
                        Toast.error({
                            content: '邮箱格式不正确！',
                            duration: 3,
                        });
                        isNext = false;
                    } else {
                        if (values.password.length < 6) {
                            Toast.error({
                                content: '密码长度最少6位！',
                                duration: 3,
                            });
                            isNext = false;
                        }
                    }
                }
            } else {
                if (!match.test(values.email)) {
                    Toast.error({
                        content: '请输入正确的邮箱！',
                        duration: 3,
                    });
                    isNext = false;
                } else {
                    if (values.password.length < 6) {
                        Toast.error({
                            content: '密码长度最少6位！',
                            duration: 3,
                        });
                        isNext = false;
                    }
                }
            }
        }
        return isNext;
    };

    // 发送邮箱
    const getEmailCodeBtn = () => {
        props.sendEmail();
    };

    // 登陆
    const handleSubmit = async (values: any) => {
        const next = rules(values);
        if (next) {
            let res: any = {};
            if (props.isregister) {
                const {email, password, verify_key} = values;
                res = await AuthUser.Register({email, password, verify_key});
            } else {
                const {email, password} = values;
                res = await AuthUser.Login({
                    email,
                    password,
                });
            }
            if (res.status) {
                if (props.isregister) {
                    Toast.success({
                        content: '注册成功！',
                        duration: 3,
                    });
                    props.goRegister();
                } else {
                    Toast.success({
                        content: '登陆成功！',
                        duration: 3,
                    });
                    saveToken(res.data.token);
                    // setuserInfo(res.data.userInfo);
                    props.handleOkLogin();
                }
            } else {
                Toast.error({
                    content: res.data.error,
                    duration: 3,
                });
            }
        }
    };
    return (
        <Form onSubmit={(values) => handleSubmit(values)} labelPosition="left">
            {({formState, values, formApi}) => (
                <>
                    {props.isregister ? (
                        <div
                            style={{width: '100%', display: 'flex', alignItems: 'center'}}
                        >
                            <div style={{width: '100%'}}>
                                <Form.Input
                                    onChange={(e) => {
                                        props.changeEmail(e);
                                    }}
                                    noLabel={true}
                                    prefix={<IconMail/>}
                                    showClear
                                    field="email"
                                    label="邮箱"
                                    trigger="change"
                                    placeholder="请输入邮箱账号"
                                />
                            </div>
                            <Button
                                disabled={props.isGetEmailCode}
                                onClick={getEmailCodeBtn}
                                style={{width: '30%'}}
                                type="tertiary"
                            >
                                {props.getEmailCode}
                            </Button>
                        </div>
                    ) : (
                        <Form.Input
                            onChange={(e) => {
                                props.changeEmail(e);
                            }}
                            noLabel={true}
                            prefix={<IconMail/>}
                            field="email"
                            label="邮箱"
                            style={{width: '100%'}}
                            trigger="change"
                            placeholder="请输入邮箱账号"
                        />
                    )}
                    {props.isregister ? (
                        <Form.Input
                            prefix={<IconHash/>}
                            noLabel={true}
                            field="verify_key"
                            label="验证码"
                            style={{width: '100%'}}
                            trigger="change"
                            placeholder="请输入验证码"
                        />
                    ) : (
                        ''
                    )}
                    <Form.Input
                        type="password"
                        prefix={<IconKey/>}
                        noLabel={true}
                        field="password"
                        label="密码"
                        style={{width: '100%'}}
                        trigger="change"
                        placeholder="请输入密码"
                    />
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                        }}
                    >
                        <p>
                            <span style={{color: 'var(--semi-color-text-0)'}}>Or</span>
                            <Button
                                onClick={register}
                                theme="borderless"
                                style={{
                                    color: 'var(--semi-color-primary)',
                                    marginLeft: 10,
                                    cursor: 'pointer',
                                }}
                            >
                                {props.isregister ? '登 陆' : '注册'}
                            </Button>
                        </p>
                        <Button htmlType="submit" type="tertiary">
                            {!props.isregister ? '登 陆' : '注册'}
                        </Button>
                    </div>
                </>
            )}
        </Form>
    );
};
